from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.viewsets import GenericViewSet
from django_redis import get_redis_connection
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from users import constants
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, \
    AddressTitleSerializer, AddUserBrowsingHistorySerializer, SKUSerializer
from rest_framework.permissions import IsAuthenticated
from users.models import User
from carts.utils import merge_cart_cookie_to_redis


class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """

    def post(self, request, *args, **kwargs):
        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 仿照drf jwt扩展对于用户登录的认证方式，判断用户是否认证登录成功
        # 如果用户登录认证成功，则合并购物车
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            merge_cart_cookie_to_redis(request, user, response)

        return response


# 请求方式：POST /browse_histories/

# class UserBrowsingHistoryView(CreateAPIView):
class UserBrowsingHistoryView(CreateAPIView):
    """
    用户历史浏览记录
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    # def post(self, request):
    #     # 检验参数
    #     sku = self.get_serializer(instance=request.data)
    #     sku.is_valid(raise_exception=True)
    #     sku.save()
    #     return Response(sku.data)

    def get(self, request):
        """
        获取浏览记录
        :param request:
        :return:
        """
        user_id = request.user.id

        redis_key = 'history_%s' % user_id

        redis_conn = get_redis_connection('history')
        # 取出redis中的数据
        history_list = redis_conn.lrange(redis_key, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)

        skus = []
        # 按顺序取出列表中的数据
        for sku_id in history_list:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(skus, many=True)

        return Response(serializer.data)


class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):

    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

    # 用户增删改查的都是自己列表的地址

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        显示用户所有的地址数据
        :param request:
        :return:
        """
        # 1 查询数据库
        address = self.get_queryset()
        # 2 序列化数据
        serializer = self.get_serializer(address, many=True)
        # 3 返回数据
        # 从request中取出user
        user = self.request.user
        id = user.id

        return Response({
            "user_id": user.id,
            "default_address_id": user.default_address_id,
            "limit": constants.USER_ADDRESS_COUNTS_LIMIT,
            "addresses": serializer.data
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        增加地址
        :param request:
        :return:
        """
        # # 1 获取参数
        # data = request.data
        # # 2 序列化校验参数
        # serializer = self.get_serializer(data=data)
        # serializer.is_valid(raise_exception=True)
        # # 3 保存数据
        # serializer.save()
        # # 4 返回数据
        # return Response(serializer.data)
        # 可以用CreateModelMixin
        count = request.user.addresses.count()
        if count > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # PUT delete /addresses/<pk>/
    def destroy(self, request, pk):
        """
        逻辑删除地址
        :param request:
        :param pk:
        :return:
        """
        # 　获取参数
        address = self.get_object()
        # 更新数据库is_delete为True
        address.is_deleted = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    # def updata(self, request, pk):
    #     """
    #     修改地址
    #     :param request:
    #     :param pk:
    #     :return:
    #     """
    #     # 1 获去参数 data = request.data
    #     # 修改对象
    #     address = self.get_object()
    #     # 序列化校验参数
    #     serializer = self.get_serializer(instance=address, data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     return Response(serializer.data)

    @action(methods=['PUT'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        :param request:
        :param pk:
        :return:
        """
        # 获取要修改的对象和参数
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['PUT'], detail=True)
    def title(self, request, pk):
        # 获取修改对象
        address = self.get_object()
        # 序列化校验数据
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 返回数据
        return Response(serializer.data)


# 请求方式：GET /emails/verification/?token=xxx
class VerifyEmailView(APIView):
    def get(self, request):
        """
        邮箱认证
        :param request:
        :return:
        """
        # 1 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 2 验证token
        user = User.check_verify_email_token(token)
        # 3 如果user不存在直接返回
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        # 4 如果用户存在email_active变为true
        user.email_active = True
        user.save()
        return Response({'message': 'OK'})


# Create your views here.

# PUT /email/
class EmailView(UpdateAPIView):
    """
    更改邮箱
    """
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):
        return self.request.user

        # def put(self, request):
        #     #  1 获取参数
        #     # 2 序列化器检验参数
        #     # 3 更改数据保存到数据库
        #     # 4 返回数据


# 请求方式： GET /user/
class UserDetailView(RetrieveAPIView):
    """
    用户中心详细信息
    """
    # 权限验证
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        # 返回当前用户请求对象
        # 在类视图中,继承的APIView中可以通过类对象获取reques
        # 在django的请求request对象中, user属性表明当前求情用户对象
        return self.request.user


# GET usernames/(?P<username>\w{5,20})/count/
class UsernameCountView(APIView):
    """
    验证用户是否存在
    """

    def get(self, request, username):
        """
        判断用户名是否存在
        :param request:
        :param username:
        :return:
        """
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }
        return Response(data=data)


# GET mobiles/(?P<mobile>1[3-9]\d{9})/count
class MobileCountView(APIView):
    """
    判断手机号是否存在
    """

    def get(self, request, mobile):
        """
        判断手机号是否存在
        :param request:
        :param mobile:
        :return:
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            "mobile": mobile,
            "count": count
        }
        return Response(data=data)


# POST /users/
class UserView(CreateAPIView):
    """
    注册
    传入参数：
        username, password, password2, sms_code, mobile, allow
    """
    serializer_class = CreateUserSerializer
